import { Component } from '@angular/core';
import { IonicPage, ToastController } from 'ionic-angular';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { HttphandleProvider } from '../../providers/httphandle/httphandle';
import { LocalstorageProvider } from '../../providers/localstorage/localstorage';
// import { Location } from '@angular/common';
import { Tools } from '../../tools/tools';
import { Router } from '@angular/router';
import { NativePageTransitions } from '@ionic-native/native-page-transitions';
import { Network } from '@ionic-native/network';

@IonicPage()
@Component({
  selector: 'page-binding-phone',
  templateUrl: 'binding-phone.html',
})
export class BindingPhonePage extends Tools{
  private phoneGroup : FormGroup;
  private rightVerification: number;  // 得到的正确的验证码
  private codealreadysend: boolean = false
  private waitNum:number = 30
  private waitMsg:string = '获取验证码'

  constructor(
    private formBuilder: FormBuilder,
    private toastCtrl: ToastController,
    private http: HttphandleProvider,
    private loc: LocalstorageProvider,
    protected route: Router,
    protected nativePageTransitions: NativePageTransitions,
    protected network: Network
  ) {
    super(route, nativePageTransitions, network)
    this.phoneGroup = this.formBuilder.group({
      phone: ['', Validators.compose([Validators.required,Validators.maxLength(11),Validators.minLength(11)])],
      verification: ['', Validators.compose([Validators.required,Validators.maxLength(4),Validators.minLength(4)])],
    });
  }
  // 返回上一个页面
  back () {
    this.openPage('accountNumber')
  }
  // 开启倒计时
  startCountDown(){
    if (this.waitNum == 0) {
      this.codealreadysend = false
      this.waitMsg = '获取验证码'
      this.waitNum = 30;
    } else {
      this.codealreadysend = true
      this.waitMsg = this.waitNum + '秒后重新发送'
      this.waitNum--;
      setTimeout(() => {
        this.startCountDown()
      },1000)
    }
  }
  // 发送修改手机号请求
  changePhone(){
    if (this.rightVerification == this.phoneGroup.value.verification) {
      console.log(this.phoneGroup.value)
      // 发送请求
      // 获取当前用户的staffid

      this.http.get('/app/rest/v2/services/yes_ReBindingService/changePhoneNumb', {
        verfication: this.phoneGroup.value.verification,
        phoneNumber: this.phoneGroup.value.phone
      }).then(res => {
        if (res.success) {
          console.log('修改手机号成功',res)
          this.toastCtrl.create({
            message: '修改手机号成功',
            position: 'top',
            duration: 1000
          }).present();
          // 修改成功后返回上一个页面
          this.back()
        } else {
          this.toastCtrl.create({
            message: res.error,
            position: 'top',
            duration: 1000
          }).present();
          console.log('修改手机号失败',res.error)
        }
      }).catch(err => {
        if (err.status == 401) {
          this.http.getToken((res) => {
            this.loc.set('token',res.json())
            this.changePhone()
          })
        } else {
          this.toastCtrl.create({
            message: err.errMsg || err,
            position: 'top',
            duration: 1000
          }).present()
        }
      })
    } else {
      this.toastCtrl.create({
        message: '验证码错误，请重新输入',
        position: 'top',
        duration: 1000
      }).present();
    }
  }
  // 发送短信验证码请求
  sendmsg(event){
    event.preventDefault()
    if (this.phoneGroup.value.phone && this.phoneGroup.value.phone.length == 11) {
      // 获取短信验证码
      if (this.codealreadysend) {
        return false  // 如果已经发送不执行任何操作
      }
      this.http.get('/app/rest/v2/services/yes_ReBindingService/byPhoneNumbGetVerification',{
        phoneNumber: this.phoneGroup.value.phone
      }).then(res => {
        if (res.success) {
          this.startCountDown()
          this.rightVerification = res.success
          this.toastCtrl.create({
            message: '发送短信验证码成功',
            position: 'top',
            duration: 1000
          }).present();
          console.log('获取短信验证码成功',res)
      } else {
        this.toastCtrl.create({
          message: res.error,
          position: 'top',
          duration: 1000
        }).present();
        console.log('发送短信验证码失败',res.error)
      }
      }).catch(err => {
        if (err.status == 401) {
          this.http.getToken((res) => {
            this.loc.set('token',res.json())
            this.sendmsg(event)
          })
        } else {
          this.toastCtrl.create({
            message: err.errMsg || err,
            position: 'top',
            duration: 1000
          }).present()
          console.log('获取短信验证码失败',err)
        }
      })
    } else {
      this.toastCtrl.create({
        message: '请先输入合法的手机号',
        position: 'top',
        duration: 1000
      }).present();
    }
  }

}
